package com.moonshineproject.plugin.update
{
	import air.update.events.DownloadErrorEvent;
	import air.update.events.StatusUpdateErrorEvent;
	import air.update.events.StatusUpdateEvent;
	import air.update.events.UpdateEvent;
	
	import com.moonshineproject.plugin.PluginBase;
	import com.riaspace.nativeApplicationUpdater.NativeApplicationUpdater;
	
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	import mx.core.FlexGlobals;
	import mx.events.FlexEvent;

	public class UpdatePlugin extends PluginBase
	{
		protected var updater:NativeApplicationUpdater;
		protected var updateFound:Boolean;
		
		private static const UPDATE_URL:String = "http://thewaxup.com/moonshine/update.xml";
	
		override public function get name():String			{ return "Update"; }
		override public function get author():String		{ return "Moonshine Project Team"; }
		override public function get description():String	{ return "Provides auto-update functionality."; }
		
	
		override public function get activatedByDefault():Boolean { return true; }
		
		public function UpdatePlugin()
		{
			super();
		}
		
		override public function activate():void
		{
			super.activate();

			registerCommand('update', update);

			// Delay a bit so stuff can be drawn and whatnot
			var t:Timer = new Timer(1000, 1);
			t.addEventListener(TimerEvent.TIMER, lookForUpdate);
			t.start();
		}
		
		protected function lookForUpdate(e:Event):void
		{
			updater = new NativeApplicationUpdater();
			updater.updateURL = UPDATE_URL;
			updater.addEventListener(StatusUpdateEvent.UPDATE_STATUS, handleUpdateStatus);
			updater.addEventListener(StatusUpdateErrorEvent.UPDATE_ERROR, handleUpdateError);
			updater.initialize();
			updater.currentState = NativeApplicationUpdater.BEFORE_CHECKING;
			updater.checkForUpdate();
		}
		
		protected function handleUpdateStatus(event:StatusUpdateEvent):void
		{
			if (event.available)
			{
				updateFound = true;
				notice("New version of Moonshine found. Type 'update' to fetch & install it.");
			}
		}
		
		protected function handleUpdateError(event:StatusUpdateErrorEvent):void
		{
			// No connection?
		}
		
		public function update(args:Array):void
		{
			if (updateFound)
			{
				updater.downloadUpdate();
				updater.addEventListener(UpdateEvent.DOWNLOAD_COMPLETE, handleDownloadComplete);
				updater.addEventListener(DownloadErrorEvent.DOWNLOAD_ERROR, handleDownloadError);
				print("Download started, will install when it's home.");
			}
			else
			{
				print("No newer version found.");
			}
		}
		
		protected function handleDownloadError(event:Event):void
		{
			error("Couldn't download update. Sorry.");
		}
		
		protected function handleDownloadComplete(event:Event):void
		{
			print("Download complete, installing update.");
			updater.installUpdate();
		}
		
	}
}